import type { App } from 'vue';
import type { I18nOptions } from 'vue-i18n';
import { createI18n } from 'vue-i18n';

import type { LocaleType } from '#/config';

import en from './lang/en';
import zh_CN from './lang/zh_CN';

type I18nInstance = ReturnType<typeof createI18n>;

export let i18n: I18nInstance;

// 浏览器语言
export const getLang = (): LocaleType => {
  const navLang = ['zh-CN', 'zh', 'zh-HK'].includes(navigator.language) ? 'zh_CN' : 'en';
  const localLanguage = localStorage.getItem('localLanguage') as LocaleType;
  return localLanguage || navLang;
};

export const setLang = (lang: LocaleType): void => {
  localStorage.setItem('localLanguage', lang);
};

setLang(getLang());

function createI18nOptions(): I18nOptions {
  const messages = {
    en: en.message,
    zh_CN: zh_CN.message,
  };

  return {
    legacy: false,
    locale: getLang(),
    fallbackLocale: 'zh_CN', // 如果没有找到要显示的语言则默认显示
    messages,
    availableLocales: ['zh_CN', 'en'],
    sync: false,
    silentTranslationWarn: true, // 控制台上不打印警告
    missingWarn: false,
    silentFallbackWarn: true,
  };
}

export function elementLocale() {
  return getLang() === 'zh_CN' ? zh_CN.message.elementLocale : en.message.elementLocale;
}

// setup i18n instance with glob
export async function setupI18n(app: App) {
  const options = createI18nOptions();
  i18n = createI18n(options) as I18nInstance;
  app.use(i18n);
}
